﻿using System;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
using System.Web.Mvc;
using System.Web.Routing;

namespace Solution
{
    /// <summary>
    /// ASP.NET MVC 错误过滤
    /// </summary>
    public class MvcExceptionFilter : HandleErrorAttribute
    {
        #region 公共方法

        public override void OnException(ExceptionContext filterContext)
        {
            // string errorMsg = string.Format("controller:{0} \n action:{1}",context.ActionContext.ControllerContext.RouteData.Route.);
            //context.RequestContext.RouteData.DataTokens
            //var message = context.Exception.StackTrace;
            //if (context.Exception.InnerException != null)
            //    message = context.Exception.InnerException.StackTrace;
            //filterContext.Result =filterContext.Request.CreateResponse(HttpStatusCode.Forbidden, rs, "application/json");
            //记录日志
            Logger.Error("system", filterContext.Exception);


            //错误信息
            string error;
            if (filterContext.Exception is ShowException)  //自定义错误
            {
                error = filterContext.Exception.Message;
            }
            else
            {
                error = ExceptionExtension.GetAllMessages(filterContext.Exception);
            }

            //如果是ajax则返回一个json的结果
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                var result = new StandardJsonResult();
                result.Fail(error);
                filterContext.Result = result;
            }
            else  //默认跳转页面
            {
                filterContext.Controller.TempData["ErrorMsg"] = error;
                filterContext.Result = new RedirectToRouteResult(new
            RouteValueDictionary(new { controller = "Error", action = "Index" }));

            }
            //context.Response = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            base.OnException(filterContext);
        }

        #endregion 公共方法
    }
}